Passed
Branchmaster (f4ca07)
by Plamen
01:26
created

table.js ➔ ... ➔ this.DrawCellFromObject   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 5
eloc 9
c 3
b 1
f 0
nc 4
nop 3
dl 0
loc 13
rs 9.3333
1
var strAsc = String.fromCharCode(9650); //▲
2
var strDesc = String.fromCharCode(9660);//▼
3
var xmlhttp;
4
var d;
5
6
var table = new function () {
7
    this.rq = null;
8
    this.tail = [];
9
10
    this.ReloadData = function (tableId) {
11
        var request = {};
12
        this.BuildRequest(request, tableId);
13
        this.LoadData(tableId, request);
14
    };
15
16
    this.BuildRequest = function (request, crntTableId, skipPropertyArray) {
17
        this.rq = request;
18
        this.checkSkip = function (skipProperty) {
19
            var result = false;
20
            if (skipPropertyArray && Object.prototype
21
                    .toString.call(skipPropertyArray) === '[object Array]') {
22
                if (skipPropertyArray.indexOf(skipProperty) >= 0) {
23
                    result = true;
24
                }
25
            }
26
            return result;
27
        };
28
        this.getSort = function () {
29
            var table = document.getElementById(crntTableId);
30
            var thTags = table.getElementsByTagName("thead")[0]
31
                    .getElementsByTagName("th");
32
            for (var i = 0; i < thTags.length; i++) {
33
                if (thTags[i].getElementsByTagName("a")[0] && thTags[i]
34
                        .getElementsByTagName("a")[0].getElementsByTagName("span")
35
                        .length === 1
36
                        ) {
37
                    var order = thTags[i].getElementsByTagName("a")[0]
38
                            .getElementsByTagName("span")[0].innerHTML;
39
                    if (order.length === 1) {
40
                        this.rq.colNo = i;
41
                        this.rq.colOrd = (order === window.strDesc) ?
42
                                "desc" : "asc";
43
                    }
44
                }
45
            }
46
        };
47
        this.getFilter = function () {
48
            var r = this.getFilterFieldsByTbaleID(crntTableId);
49
            if (r.filter !== null) {
50
                this.rq.filter = r.filter;
51
            }
52
            if (r.filterBy !== null) {
53
                this.rq.filterBy = r.filterBy;
54
            }
55
        };
56
57
        /* Build request object */
58
        if (!this.checkSkip("sort")) {
59
            this.getSort();
60
        }
61
        if (!this.checkSkip("filter")) {
62
            this.getFilter();
63
        }
64
65
        this.rq.tableId = crntTableId;
66
        return this.rq;
67
    };
68
69
    this.RequestToUrl = function (rq) {
70
        var url = location.pathname + ".json" + location.search;
71
        if (typeof rq === "object") {
72
            var getUrlVarName = {
73
                colNo: "col", colOrd: "ord", filter: "filter",
74
                filterBy: "filter-by", pageNo: "pg", exportType: "export",
75
                tableId: "table-id"
76
            };
77
            var flagFirst = location.search.length < 1 ? true : false;
78
            var length = rq.length;
79
            for (var i = 0; i < length.length; i++) {
80
                var clue = flagFirst === true ? "?" : "&";
81
                url += clue + getUrlVarName[i] + "=" + rq[i];
82
                flagFirst = false;
83
            }
84
        }
85
        return url;
86
    };
87
88
    this.Filter = function (field) {
89
        var request = {};
90
        var isSelect = field.tagName.toLowerCase() === "select";
91
        if (isSelect) {
92
            var f = field.parentNode.parentNode.getElementsByTagName("input")[0];
93
            if ('' === f.value) {
94
                return;
95
            }
96
            var crntTableId = f.getAttribute("data-table-id");
97
        } else {
98
            crntTableId = field.getAttribute("data-table-id");
99
        }
100
        var exRq = this.rq;
101
        this.BuildRequest(request, crntTableId);
102
        if (exRq === null) {
103
            this.LoadData(crntTableId, request);
104
        } else if (request.filter !== exRq.filter ||
105
                request.filterBy !== exRq.filterBy
106
                ) {
107
            this.LoadData(crntTableId, request);
108
        }
109
    };
110
111
    this.GoPage = function (lnk) {
112
        var request = {};
113
        var table = this.getParent(lnk, "table");
114
        var crntTableId = table.getAttribute("id");
115
        this.BuildRequest(request, crntTableId);
116
        //check & serve pagination jump links
117
        var jumpDir = lnk.innerHTML.trim().substr(0, 1);
118
        if (jumpDir === "+" || jumpDir === "-") {
119
            var current = table.querySelector("tfoot .paging .a").innerHTML;
120
            var jump = lnk.innerHTML.replace("K", "000").replace("M", "000000000");
121
            var jumpPage = (parseInt(current) + parseInt(jump));
122
            lnk.parentNode.setAttribute("data-page", jumpPage);
123
            lnk.style.transform = "none";
124
        }
125
        request.pageNo = lnk.parentNode.hasAttribute("data-page") ?
126
                lnk.parentNode.getAttribute("data-page") :
127
                lnk.innerHTML;
128
        this.LoadData(crntTableId, request);
129
        return false;
130
    };
131
132
    this.Export = function (lnk, eType) {
133
        var request = {};
134
        var crntTableId = this.getParent(lnk, "table").getAttribute("id");
135
        this.BuildRequest(request, crntTableId);
136
        request.exportType = ["CSV", "Excel"].indexOf(eType) >= 0 ? eType : "csv";
137
        window.open(this.RequestToUrl(request));
138
        return false;
139
    };
140
141
    this.Sort = function (colNo, lnk) {
142
        var request = {};
143
        var crntTableId = this.getParent(lnk, "table").getAttribute("id");
144
        this.BuildRequest(request, crntTableId);
145
        if (Math.round(colNo) === request.colNo) {
146
            request.colOrd = request.colOrd === "asc" ? "desc" : "asc";
147
        } else {
148
            request.colNo = Math.round(colNo);
149
            request.colOrd = "asc";
150
        }
151
        this.LoadData(crntTableId, request);
152
        /* Clear and add new sort arrow */
153
        var headSpans = this.getParent(lnk, "thead").getElementsByTagName("span");
154
        var length = headSpans.length;
155
        for (var i = 0; i < length; i++) {
156
            headSpans[i].innerHTML = "";
157
        }
158
        lnk.getElementsByTagName("span")[0].innerHTML = (request.colOrd === "desc" ? window.strDesc : window.strAsc);
159
    };
160
161
    this.DrawSection = function (tableContainer, dt, tSection) {
162
        var section = tSection === "tfoot" ? "tfoot" : "tbody";
163
        tSection = document.getElementById(tableContainer).
164
                getElementsByTagName(section)[0];
165
        this.clearSection(tSection);
166
        for (var i = 0; i < dt.length; i++) {
167
            var row = dt[i];
168
            var tRow = document.createElement("tr");
169
170
            this.DrawRow(row, tRow);
171
172
            tSection.appendChild(tRow);
173
            if (section === "tfoot") {
174
                this.footerProcessPaginationLinks(tSection);
175
            }
176
            this.AppendRowCalback(tableContainer);
177
        }
178
    };
179
180
    this.DrawRow = function (row, tRow) {
181
        var length = row.length;
182
        for (var i = 0; i < length; i++) {
183
            var tCell = document.createElement("td");
184
            if (typeof row[i] === "string" ||
185
                    typeof row[i] === "number"
186
                    ) {
187
                tCell.innerHTML = row[i];
188
            } else if (typeof row[i] === "object") {
189
                this.DrawCellFromObject(row, row[i], tCell);
190
            }
191
            tRow.appendChild(tCell);
192
        }
193
    };
194
195
    this.DrawCellFromObject = function (row, cell, tCell) {
196
        var length = row[cell].length;
197
        for (var i = 0; i < length; i++) {
198
            if (typeof row[cell][i] === "string") {
199
                tCell.innerHTML = row[cell][i];
200
            } else if (typeof row[cell][i] === "object") {
201
                var length2 = row[cell][i].length;
202
                for (var j = 0; j < length2; j++) {
203
                    tCell.setAttribute(j, row[cell][i][j]);
204
                }
205
            }
206
        }
207
    };
208
209
    this.footerProcessPaginationLinks = function (tSection) {
210
        var pLinks = tSection.querySelectorAll(".paging a");
211
        if (pLinks.length > 0) {
212
            for (var j = 0; j < pLinks.length; j++) {
213
                pLinks[j].setAttribute("href", "javascript:void(0);");
214
                pLinks[j].setAttribute("onclick", "return table.GoPage(this);");
215
            }
216
        }
217
    };
218
219
    this.clearSection = function (tSection) {
220
        if (this.iePrior(9)) {
221
            if (tSection.firstChild) {
222
                while (tSection.firstChild) {
223
                    tSection.removeChild(tSection.firstChild);
224
                }
225
            }
226
        } else {
227
            tSection.innerHTML = "";
228
        }
229
    };
230
231
    this.SetTheTableColumnsHoverEffect = function (tableContainer) {
232
        if (this.iePrior(9)) {
233
            return;
234
        }
235
        var tContainer = document.getElementById(tableContainer);
236
        var tHcells = tContainer.rows[0].cells;
237
        for (var i = 0; i < tHcells.length; i++) {
238
            if (tHcells[i].firstChild.tagName === "A") {
239
                tHcells[i].firstChild.setAttribute("onmouseover", "table.ColumnHover('" + tableContainer + "'," + i + ");");
240
                tHcells[i].firstChild.setAttribute("onmouseout", "table.ColumnHover('" + tableContainer + "');");
241
            }
242
        }
243
        var pLinks = tContainer.querySelectorAll("tfoot .paging a");
244
        if (pLinks.length > 0) {
245
            for (var j = 0; j < pLinks.length; j++) {
246
                pLinks[j].setAttribute("href", "javascript:void(0);");
247
                pLinks[j].setAttribute("onclick", "return table.GoPage(this);");
248
            }
249
        }
250
    };
251
252
    this.ColumnHover = function (tableContainer, index) {
253
        if (this.iePrior(9)) {
254
            return;
255
        }
256
        var tRow = document.getElementById(tableContainer).rows;
257
        index = Math.round(index);
258
        for (var i = 0; i < (tRow.length - 1); i++) {
259
            if (index >= 0) {
260
                tRow[i].cells[index].setAttribute("lang", "col-hover");
261
            } else {
262
                for (var j = 0; j < tRow[i].cells.length; j++) {
263
                    if (tRow[i].cells[j].lang) {
264
                        tRow[i].cells[j].removeAttribute("lang");
265
                    }
266
                }
267
            }
268
        }
269
    };
270
271
    this.getFilterFieldsByTbaleID = function (tableID) {
272
        var fields = {filterBy: null, filter: null};
273
        var filterDiv = this.getFilterDivByTableIDOrNull(tableID);
274
        if (filterDiv !== null) {
275
            var selectObj = filterDiv.getElementsByTagName("select")[0];
276
            var textObj = filterDiv.getElementsByTagName("input")[0];
277
            fields.filterBy = (selectObj === null || selectObj.options[selectObj.selectedIndex].value === "all") ? null : selectObj.options[selectObj.selectedIndex].value;
278
            fields.filter = (textObj === null || textObj.value.length === 0) ? null : encodeURIComponent(textObj.value.trim());
279
        }
280
        return fields;
281
    };
282
283
    this.getFilterDivByTableIDOrNull = function (tableID) {
284
        var res = null;
285
        if (document.getElementById(tableID).parentNode.getElementsByTagName("div").length > 0) {
286
            for (var i = 0; i < document.getElementById(tableID).parentNode.getElementsByTagName("div").length; i++) {
287
                if (document.getElementById(tableID).parentNode.getElementsByTagName("div")[i].getAttribute("class") === "filter") {
288
                    return document.getElementById(tableID).parentNode.getElementsByTagName("div")[i];
289
                }
290
            }
291
292
        }
293
        return res;
294
    };
295
296
    this.LoadData = function (tableContainer, rq) {
297
        this.setVisability(tableContainer, false);
298
        if (window.XMLHttpRequest) {
299
            xmlhttp = new XMLHttpRequest();/* code for IE7+, Firefox, Chrome, Opera, Safari */
300
        } else { /** global: ActiveXObject */
301
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");/*code for IE6, IE5 */
0 ignored issues
show
Bug introduced by
The variable ActiveXObject seems to be never declared. If this is a global, consider adding a /** global: ActiveXObject */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
302
        }
303
        for (var i = 0; i < this.tail.length; i++) {
304
            var ex_xmlhttp = this.tail.shift();
305
            ex_xmlhttp.abort();
306
        }
307
        xmlhttp.onreadystatechange = function () {
308
            if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
309
                d = JSON.parse(xmlhttp.responseText);
310
                table.DrawSection(tableContainer, d.body);
311
                table.DrawSection(tableContainer, d.footer, "tfoot");
312
                table.LoadEndCalback(tableContainer);
313
                table.setVisability(tableContainer, true);
314
                if (typeof rq === "object") {
315
                    table.ColumnHover(tableContainer, rq.colNo);
316
                }
317
            }
318
        };
319
        xmlhttp.open("GET", this.RequestToUrl(rq), true);
320
        xmlhttp.send();
321
        this.tail.push(xmlhttp); //put in tail to may later abort any previous
322
    };
323
324
    this.setVisability = function (tableContainer, rq) {
325
        var tbl = document.getElementById(tableContainer);
326
        if (rq === true) {
327
            tbl.style.filter = "none";
328
            tbl.style.opacity = "1";
329
            tbl.style.cursor = "auto";
330
        } else if (rq === false) {
331
            tbl.style.filter = "blur(1px)";
332
            tbl.style.opacity = "0.8";
333
            tbl.style.cursor = "wait";
334
        } else {
335
            console.log("table error in the rq value"); /*Shows error*/
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
336
        }
337
    };
338
339
    this.getParent = function (obj, objType) {
340
        while (obj && obj.tagName !== objType.toUpperCase()) {
341
            obj = obj.parentNode;
342
        }
343
        return obj;
344
    };
345
346
    this.init = function (tableId) {
347
        this.SetTheTableColumnsHoverEffect(tableId);
348
    };
349
350
    this.iePrior = function (v) {
351
        var rv = false;
352
        if (/** global: navigator */ navigator.appName === 'Microsoft Internet Explorer') {
0 ignored issues
show
Bug introduced by
The variable navigator seems to be never declared. If this is a global, consider adding a /** global: navigator */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
353
            var ua = navigator.userAgent;
354
            var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
355
            if (re.exec(ua) !== null) {
356
                rv = parseFloat(RegExp.$1);
357
            }
358
            rv = rv < v ? true : false;
359
        }
360
        return rv;
361
    };
362
    this.loadJS = function (src) {
363
        var s = document.createElement('script');
364
        s.src = src;
365
        document.getElementsByTagName('head')[0].appendChild(s);
366
    };
367
    this.loadCSS = function (src) {
368
        var s = document.createElement('link');
369
        s.href = src;
370
        s.rel = "stylesheet";
371
        document.getElementsByTagName('head')[0].appendChild(s);
372
    };
373
374
    this.LoadEndCalback = function (tableId) {
375
        if (tableId) {/*Allows override*/
0 ignored issues
show
Comprehensibility Documentation Best Practice introduced by
This code block is empty. Consider removing it or adding a comment to explain.
Loading history...
376
        }
377
    };
378
    this.AppendRowCalback = function (tableId) {
379
        if (tableId) {/*Allows override*/
0 ignored issues
show
Comprehensibility Documentation Best Practice introduced by
This code block is empty. Consider removing it or adding a comment to explain.
Loading history...
380
        }
381
    };
382
};
383
384
/** Moves custom created filter to the Table's filter
385
 * @param {string} filterId
386
 * @param {string} tableId
387
 * @param {boolean} delay - needed in case the table is istill not executed */
388
function moveSelectorToTheTableFilter(filterId, tableId, delay) {
389
    if (delay === true) {
390
        setTimeout(function () {
391
            var filterDiv = document.getElementById(tableId)
392
                    .getElementsByTagName("div")[0];
393
            filterDiv.appendChild(document.getElementById(filterId));
394
        }, 500);
395
    } else {
396
        var filterDiv = document.getElementById(tableId)
397
                .getElementsByTagName("div")[0];
398
        filterDiv.appendChild(document.getElementById(filterId));
399
    }
400
}
401
function changeListCustomFilter(selectObj) {
402
    var fId = selectObj.options[selectObj.selectedIndex].value;
403
    var hasValue = fId !== "{!--Empty--!}";
404
    var varName = selectObj.getAttribute("name");
405
    var varPos = document.URL.indexOf(varName);
406
    if (varPos > 0) {
407
        var url = hasValue ?
408
                document.URL.substring(0, varPos) :
409
                document.URL.substring(0, (varPos - 1));
410
    } else {
411
        var separator = document.URL.indexOf("?") > 0 ? "&" : "?";
412
        url = document.URL + (hasValue ? separator : "");
413
    }
414
    var newUrl = url + (hasValue ? (varName + "=" + fId) : "");
415
    location.assign(newUrl);
416
}
417
418
419
function tablesLoadData() {
420
    var tables = document.getElementsByTagName("table");
421
    var envPrior9 = table.iePrior(9);
422
    for (var i = 0; i < tables.length; i++) {
423
        var isProcessable = envPrior9 ?
424
                typeof tables[i]["data-table"] !== 'undefined' :
425
                tables[i].hasAttribute("data-table");
426
        if (isProcessable && tables[i].getAttribute("data-table") === "js") {
427
            table.LoadData(tables[i].id);
428
            table.SetTheTableColumnsHoverEffect(tables[i].id);
429
        }
430
    }
431
    if (table.iePrior(10)) {
432
        table.loadJS("/add/helpers/table/add/json2.js");
433
    }
434
435
    /*if(table.iePrior(8)){ //can be used to add apropriate tables links modifications
436
     // loadCSS("/add/helpers/table/add/ie7-and-down.css");
437
     }*/
438
}
439
440
/*if(window.addEventListener){window.addEventListener('load',tablesLoadData,false);} else if(window.attachEvent){window.attachEvent('onload',tablesLoadData);}*/